package com.zsr.educenter.controller;


import com.zsr.commonutils.R;
import com.zsr.commonutils.entity.vo.UcenterMemberInfoCommonVo;
import com.zsr.commonutils.util.JwtUtil;
import com.zsr.educenter.entity.UcenterMember;
import com.zsr.educenter.entity.vo.LoginVo;
import com.zsr.educenter.entity.vo.RegisterVo;
import com.zsr.educenter.entity.vo.UserInfoVo;
import com.zsr.educenter.service.UcenterMemberService;
import com.zsr.servicebase.exceptionhandler.BusinessException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 会员表 前端控制器
 * </p>
 *
 * @author zsr
 * @since 2021-06-19
 */
@Api(tags={"登录注册接口"})
@RestController
//@CrossOrigin
@RequestMapping("/educenter/ucenter")
public class UcenterMemberController {

    @Autowired
    private UcenterMemberService ucenterMemberService;

    @ApiOperation(value = "会员登录")
    @PostMapping("login")
    public R login(@RequestBody LoginVo loginVo) {
        String token = ucenterMemberService.login(loginVo);
        return R.ok().data("token", token);
    }

    @ApiOperation(value = "会员注册")
    @PostMapping("register")
    public R register(@RequestBody RegisterVo registerVo){
        ucenterMemberService.register(registerVo);
        return R.ok();
    }

    @ApiOperation(value = "根据token获取登录信息")
    @GetMapping("auth/getLoginInfo")
    public R getLoginInfo(HttpServletRequest request){
        try {
            String memberId = JwtUtil.getMemberIdByJwtToken(request);
            UserInfoVo loginInfoVo = ucenterMemberService.getLoginInfo(memberId);
            return R.ok().data("item", loginInfoVo);
        }catch (Exception e){
            e.printStackTrace();
            throw new BusinessException(20001,"error");
        }
    }

    /**
     *  [远程调用]根据id获取用户信息
     * @param id 用户id
     * @return 公共模块下的vo
     */
    @ApiOperation(value = "[远程调用]根据id获取用户信息")
    @GetMapping("getInfoUc/{id}")
    public UcenterMemberInfoCommonVo getInfo(@PathVariable String id) {
        //根据用户id获取用户信息
        UcenterMember user =ucenterMemberService.getById(id);
        System.out.println(user);
        UcenterMemberInfoCommonVo userInfoVo = new UcenterMemberInfoCommonVo();
        BeanUtils.copyProperties(user, userInfoVo);
        return userInfoVo;
    }

    /**
     * [远程调用]根据日期获取注册人数
     * @param day
     * @return
     */
    @ApiOperation(value = "[远程调用]根据日期获取注册人数")
    @GetMapping(value = "countregister/{day}")
    public Map<String,Object> registerCount(
            @PathVariable String day){
        Integer count = ucenterMemberService.countRegisterByDay(day);
        Map<String,Object> map =new HashMap<>();
        map.put("countRegister",count);
        return map;
    }
}

